package initer

import (
	"flag"
	"fmt"
	"net/http"
	"time"

	"gitee.com/yxd1990/golang-common/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

func init() {
	profile := flag.String("P", "dev", "profile")
	flag.Parse()
	logs.Info("load profile:", *profile)
	beego.BConfig.RunMode = *profile
	beego.BConfig.Listen.HTTPPort = beego.AppConfig.DefaultInt("httpport", 8181)

	if beego.BConfig.RunMode == "dev" {
		orm.Debug = true
	} else {
		orm.Debug = beego.AppConfig.DefaultBool("ormDebug", false)
	}

	maxIdle := beego.AppConfig.DefaultInt("maxIdle", 50)
	maxConn := beego.AppConfig.DefaultInt("maxConn", 300)
	sqlconn := beego.AppConfig.String("sqlconn")
	if err := orm.RegisterDataBase("default", "mysql", sqlconn, maxIdle,
		maxConn); err != nil {
		panic(err)
	}
	jwtConfig := &utils.JwtConfig{}
	jwtConfig.Secret = []byte(beego.AppConfig.DefaultString("jwtSecret", "appletree"))
	// 默认有效期30天
	jwtConfig.JwtDueTime = time.Duration(beego.AppConfig.DefaultInt64("jwtValidHours", 24*30))
	utils.InitJwt(jwtConfig)

	//logs.Async(1e3)
	err := logs.SetLogger(logs.AdapterMultiFile, fmt.Sprintf(`{"filename":"logs/common.all.log","level":%d,"separate":["error","warning"]}`, logs.LevelInformational))
	if err != nil {
		panic(err)
	}
}

func EnableCrossDomain() {
	logs.Info("EnableCrossDomain")
	//跨域设置
	var FilterGateWay = func(ctx *context.Context) {
		logs.Info("EnableCrossDomain FilterGateWay")
		ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		//允许访问源
		ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
		//允许post访问
		ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,ContentType,Authorization,accept,accept-encoding, authorization, content-type") //header的类型
		ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
		ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
		if ctx.Input.Method() == "OPTIONS" {
			ctx.ResponseWriter.WriteHeader(http.StatusOK)
		} else {
			logs.Info("request url:", ctx.Request.RequestURI)
		}
	}
	beego.InsertFilter("*", beego.BeforeRouter, FilterGateWay)
}
